package com.cheesmo.nzb.model.impl;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import com.cheesmo.nzb.model.File;
import com.cheesmo.nzb.model.NZB;

public class NzbParser extends DefaultHandler
{
	NZB nzb = new NZBImpl();
	File currentFile;
	int currentSegmentBytes = 0;
	int currentSegmentNumber = 0;
	String currentSegmentString = "";
	String currentGroup = "";
	String curElement = "";

	public NZB parse(String path) throws SAXException, FileNotFoundException, IOException
	{
		return parse(new InputSource(path));
	}

	public NZB parse(InputSource source) throws SAXException, IOException {
		NzbParser parser = new NzbParser();
		XMLReader reader = XMLReaderFactory.createXMLReader();
		reader.setContentHandler(parser);
		reader.parse(source);
		return parser.nzb;
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		if (this.curElement.equals("group"))
			this.currentGroup += new String(ch, start, length);
		else if (this.curElement.equals("segment"))
			this.currentSegmentString += new String(ch, start, length);
	}

	public void endElement(String uri, String localName, String qName) throws SAXException
	{
		if (localName.equals("file")) {
			this.nzb.addFile(this.currentFile);
		} else if (localName.equals("group")) {
			this.currentFile.addGroup(new GroupImpl(this.currentGroup));
			this.currentGroup = "";
		} else if (localName.equals("segment")) {
			this.currentFile.addSegment(new SegmentImpl(this.currentSegmentBytes, this.currentSegmentNumber, this.currentSegmentString));
			this.currentSegmentString = "";
		}
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		this.curElement = localName;
		if (localName.equals("file"))
		{
			String subject = attributes.getValue("subject");
			String poster = attributes.getValue("poster");
			String dateS = attributes.getValue("date");
			int date = 0;
			try {
				date = Integer.parseInt(dateS);
			} catch (Exception localException) {
			}
			this.currentFile = new FileImpl(poster, subject, date);
		} else if (localName.equals("group")) {
			this.currentGroup = "";
		} else if (localName.equals("segment")) {
			try {
				this.currentSegmentBytes = Integer.parseInt(attributes.getValue("bytes"));
				this.currentSegmentNumber = Integer.parseInt(attributes.getValue("number"));
			} catch (Exception localException1)
			{
			}
		}
	}
}
